package com.chenyue.cm.auth;

import com.chenyue.cm.auth.token.LoginUserInfo;
import com.chenyue.cm.auth.token.RequestUtil;
import com.chenyue.cm.exception.SysRuntimeException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author libingxing
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	static final String USER_KEY = "username";

	static final String TOKEN = "token";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Login annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
		} else {
			return true;
		}

		if (annotation == null) {
			return true;
		}

		// 获取用户凭证
		LoginUserInfo userInfo = RequestUtil.getUserInfoByRequest(request);

		// 凭证为空
		if (StringUtils.isEmpty(userInfo.getUserId())) {
			throw new SysRuntimeException("登录失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
		}

		if (userInfo.getUserId() == null) {
			throw new SysRuntimeException("登录失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
		}


		// 设置userId到request里，后续根据userId，获取用户信息
		request.setAttribute(USER_KEY, userInfo.getUserId());
		request.setAttribute(TOKEN, request.getHeader(TOKEN));

		return true;
	}
}
